<template>
  <div>

    <!-- 1.定义面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户信息</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 2.定义卡片视图 -->
    <el-card class="box-card">

      <!-- 3.定义栅格的一行 :gutter="20"定义行间距   :span="9" 占位符  -->
      <el-row :gutter="20">
        <el-col :span="9">
          <!-- 3.定义搜索框 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="14">
          <!-- 定义添加按钮-->
          <el-button type="primary" @click="addEmpInfo()" style="float: right">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户数据表格展现  border 边框线属性  -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="empId" label="员工编号" width="90"></el-table-column>
        <el-table-column prop="empName" label="员工姓名" width="90"></el-table-column>
        <el-table-column prop="phone" label="电话" width="120"></el-table-column>
        <el-table-column label="照片" width="120">
          <template slot-scope="scope">
            <img :src="scope.row.empPhoto" width="70" height="60">
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="120"></el-table-column>
        <el-table-column prop="qq" label="QQ" width="120"></el-table-column>
        <el-table-column prop="wechat" label="微信" width="150"></el-table-column>
        <el-table-column prop="edu" label="学历" width="80"></el-table-column>
        <el-table-column prop="depName" label="所在部门" width="80"></el-table-column>
        <el-table-column prop="positionName" label="职位" width="120"></el-table-column>
        <el-table-column prop="empStatus" label="状态" width="150">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.empStatus" @change="updateStatus(scope.row)"
                       active-text="在职" inactive-text="离职" active-color="#13ce66" inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="hiredate" label="入职日期" width="120"></el-table-column>
        <el-table-column prop="resignDate" label="离职日期" width="120"></el-table-column>
        <el-table-column label="操作" width="210px" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="small" @click="updateUserBtn(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteUser(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 20, 40]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 定义修改页面 当对话框关闭时,将表格数据重置-->
    <el-dialog title="修改用户信息" :visible.sync="updateDialogVisible" width="50%" @close="closeUpdateDialog">
      <!-- 定义用户提交表单数据-->
      <el-form :model="updateUserModel" ref="updateUserRef" label-width="100px">
        <el-form-item label="员工姓名" :label-width="formLabelWidth">
          <el-input v-model="updateUserModel.empName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工编号" :label-width="formLabelWidth">
          <el-input v-model="updateUserModel.empId" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth">
          <el-input v-model="updateUserModel.phone" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="QQ" :label-width="formLabelWidth">
          <el-input v-model="updateUserModel.qq" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="微信" :label-width="formLabelWidth">
          <el-input v-model="updateUserModel.wechat" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="updateUserModel.email" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="学历">
          <el-select v-model="updateUserModel.edu" placeholder="请选择" @focus="getEduInfo">
            <el-option v-for="item in edu" :key="item.id" :label="item.eduName" :value="item.eduName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门">
          <el-cascader v-model="selectedKeys" :props="props" :options="parentDepartmentList" clearable
                       @change="parentItemCatChange" @focus="getDepartmentInfo"></el-cascader>
        </el-form-item>
        <el-form-item label="职位">
          <el-select v-model="updateUserModel.positionName" placeholder="请选择" @focus="getPositionInfo"
                     @change="modifyData()">
            <el-option v-for="item in parentPositionList" :key="item.positionId" :label="item.positionName"
                       :value="item.positionId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入职日期" :label-width="formLabelWidth">
          <el-date-picker v-model="updateUserModel.hiredate" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="离职日期" :label-width="formLabelWidth">
          <el-date-picker v-model="updateUserModel.resignDate" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="头像" :label-width="formLabelWidth">
          <el-upload class="upload-demo" :action="uploadUrl" :on-preview="handlePreview" :on-remove="handleRemove"
                     :on-success="handleSuccess" list-type="picture" :limit="1">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

export default {
  data() {
    return {
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 5
      },
      userList: [],
      //部门分级信息
      selectedKeys: [],
      props: {
        // 定义子节点菜单展开方式
        expandTrigger: 'hover',
        value: 'depId', // 选中数据的value值
        label: 'depName', // 选中数据展现名称
        children: 'children', // 自选项数据
        checkStrictly: true
      },
      edu: [],
      parentDepartmentList: [],
      parentPositionList: [],
      // 记录总数是数值类型
      total: 0,
      updateEmpFormModel: {},
      formLabelWidth: '120px',
      uploadUrl: 'http://localhost:8093/user/file/empImagesUpload',
      updateDialogVisible: false,
      // 定义修改用户数据封装
      updateUserModel: {
        empName: '',
        empId: '',
        empPassword: '',
        positionId: '',
        positionName: '',
        depId: '',
        hiredate: '',
        resignDate: '',
        phone: '',
        email: '',
        qq: '',
        edu: '',
        wechat: '',
        empPhoto: ''
      }
    }
  },
  methods: {
    modifyData() {
      this.updateUserModel.positionId = this.updateUserModel.positionName
    },

    async handleRemove(file, fileList) {
      const {data: res} = await this.$http.delete("/user/file/deleteFile?key=" +
        this.updateUserModel.images).catch(function (e) {
        alert(e)
      })
      if (res.status !== 200) return this.$message.error('删除图片失败')
      this.$message.success('删除图片成功')
    },
    handlePreview(file) {
      this.imageUrlPath = file.response.data.urlPath
      this.dialogImageVisible = true
    },
    handleSuccess(response, file) {
      if (response.status !== 200) return this.$message.error('文件上传失败')
      file.name = response.data.fileName
      // 获取虚拟路径
      this.updateUserModel.images = response.data.urlPath
    },

    parentItemCatChange() {
      this.updateUserModel.depId = this.selectedKeys[this.selectedKeys.length - 1]
    },
    async getDepartmentInfo() {
      const {data: res} = await this.$http.get("/admin/addEmpInfo/getDepartmentInfo/2").catch(
        function (e) {
          alert(e)
        })
      if (res.status !== 200) return this.$message.error("查询部门信息失败")
      this.$message.success("获取部门信息成功")
      this.parentDepartmentList = res.data
    },

    async getPositionInfo() {
      if (this.selectedKeys.length === 0) return this.$message.error("请先选择部门")
      const {data: res} = await this.$http.get(`/admin/addEmpInfo/getPositionInfo/${this.updateUserModel.depId}`).catch(
        function (e) {
          alert(e)
        })
      if (res.status !== 200) return this.$message.error("获取当前部门职位信息失败")
      this.parentPositionList = res.data
      this.$message.success("获取当前部门职位信息成功")
    },

    //获取学历信息
    async getEduInfo() {
      const {data: res} = await this.$http.get("/admin/addEmpInfo/getEduInfo").catch(
        function (e) {
          alert(e)
        })
      this.edu = res.data
    },

    async getUserList() {
      const {data: result} = await this.$http('/admin/userList', {
        params: this.queryInfo
      }).catch(function (e) {
        if (e.response.status === 500) {
          alert("服务器故障")
        }
      })
      if (result.status !== 200) return this.$message.error("查询用户信息失败")
      this.userList = result.data.rows;
      this.total = result.data.total;
    },

    addEmpInfo() {
      this.$router.push("/admin/userManger/addEmp")
    },

    async updateStatus(user) {
      const {data: res} = await this.$http.put("/admin/updateEmpStatus/", user).catch(
        function (e) {
          alert(e)
        })
      if (res.status !== 200) return this.$message.error("更新用户状态失败")
      await this.getUserList()
      this.$message.success("更新用户状态成功")
    },
    handleSizeChange(pageSize) {
      this.queryInfo.pageSize = pageSize
      this.getUserList()
    },
    handleCurrentChange(pageNum) {
      this.queryInfo.pageNum = pageNum
      this.getUserList()
    },
    async updateUserBtn(user) {
      this.updateDialogVisible = true
      const {data: result} = await this.$http.get(`/admin/getEmpInfo/${user.id}`)
        .catch(function (e) {
          if (e.response.status === 500) {
            return this.$message.error("服务器错误")
          }
        })
      if (result.status === 200) {
        this.updateUserModel = result.data
      } else {
        return this.$message.error("查询失败")
      }
    },
    closeUpdateDialog() {
      // 重置表格数据
      this.$refs.updateUserRef.resetFields()
    },
    async updateUser() {
      const {data: res} = await this.$http.put('/admin/updateEmpInfo',
        this.updateUserModel).catch(function (e) {
        alert(e)
      })
      if (res.status !== 200) return this.$message.error("修改失败")
      this.$message.success("修改成功")
      this.updateDialogVisible = false
      await this.getUserList()
    },
    async deleteUser(user) {
      const result = await this.$confirm('此操作将永久删除 ' + user.empName + ' , 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)

      // 如果确认  confirm  如果取消 cancel
      if (result !== 'confirm') {
        return this.$message.info('删除取消')
      }
      const {data: res} = await this.$http.delete(`/admin/deleteEmp/${user.id}`).catch(
        function (e) {
          alert(e)
        })
      if (res.status !== 200) return this.$message.error(res.data)
      await this.getUserList()
      this.$message.success("删除成功")
    },
  },
  // 利用钩子函数实现数据查询
  mounted() {
    this.getUserList()
  }
}
</script>

<style lang="less" scoped>

</style>
